﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YJKRevitKernel.RevitObjectSerializeUtility;

namespace YJKRevitDimensionText.AnnotationSetting
{
	[Transaction(TransactionMode.Manual)]
	internal class CmdAnnotationSetting : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			string filePath = TreeViewAndDGVDisplayConstName.FilePath;
			Document document = commandData.Application.ActiveUIDocument.Document;
			Transaction transaction = new Transaction(document, "AnnotationSetting");
			FormAnnotationSetting formAnnotationSetting = new FormAnnotationSetting(document, transaction);
			try
			{
				transaction.Start();
				if (formAnnotationSetting.ShowDialog() == DialogResult.OK)
				{
					Dictionary<string, string> dicFormData = new Dictionary<string, string>();
					if (formAnnotationSetting.tabPage1.Name == formAnnotationSetting.tabControl1.SelectedTab.Name)
					{
						formAnnotationSetting.GetDGVData(dicFormData, formAnnotationSetting.dgvAttribute);
						formAnnotationSetting.SetDGVData(dicFormData, formAnnotationSetting.treeViewGridLevelProfile);
					}
					else
					{
						formAnnotationSetting.GetDGVData(dicFormData, formAnnotationSetting.dgvAttribute2);
						formAnnotationSetting.SetDGVData(dicFormData, formAnnotationSetting.treeViewSizeWord);
					}
					transaction.Commit();
					SaveOldSelectData saveOldSelectData = new SaveOldSelectData();
					if (formAnnotationSetting.tabPage1.Name == formAnnotationSetting.tabControl1.SelectedTab.Name)
					{
						saveOldSelectData.TabPageNum = 0;
						saveOldSelectData.ParentNodeName = formAnnotationSetting.treeViewGridLevelProfile.SelectedNode.Parent.Text;
						saveOldSelectData.ChildNodeName = formAnnotationSetting.treeViewGridLevelProfile.SelectedNode.Text;
					}
					else
					{
						saveOldSelectData.TabPageNum = 1;
						saveOldSelectData.ParentNodeName = formAnnotationSetting.treeViewSizeWord.SelectedNode.Parent.Text;
						saveOldSelectData.ChildNodeName = formAnnotationSetting.treeViewSizeWord.SelectedNode.Text;
					}
					if (!File.Exists(filePath))
					{
						new FileStream(filePath, FileMode.CreateNew).Close();
					}
					Exception ex;
                    new HYRevitObjectSerializeManger().TryWriteAPersistentClassByXML(filePath, saveOldSelectData, out ex, true);
				}
				else if (transaction.HasStarted())
				{
					transaction.RollBack();
				}
			}
			catch
			{
				if (transaction.HasStarted())
				{
					transaction.RollBack();
				}
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}
	}
}
